/*
 * BlockNode.cpp
 *
 *  Created on: Jul 7, 2009
 *      Author: elkobir
 */

#include "BlockNode.h"

BlockNode::BlockNode(int blockSizeInBytes) {
	_blockSizeInBytes = blockSizeInBytes;
	_addressesInBlockCount = (_blockSizeInBytes / 4) - 1;

	unsigned char* data = Utils::InitBytes(_blockSizeInBytes);

	fromBytes(data);

}
BlockNode::BlockNode(int blockSizeInBytes, unsigned char* data) {
	_blockSizeInBytes = blockSizeInBytes;
	_addressesInBlockCount = (_blockSizeInBytes / 4) - 1;

	fromBytes(data);

}

BlockNode::~BlockNode() {
	// TODO Auto-generated destructor stub
}

unsigned char* BlockNode::toBytes(){
	unsigned char* res = Utils::InitBytes(_blockSizeInBytes);
	//TODO who ever control res control his release memory

	for(unsigned int i = 0; i < (unsigned)_addressesInBlockCount; i++){
		int val = this->_addresses.at(i);
		Utils::IntToByte(val, res, i*4 );
	}

	Utils::IntToByte(_nextBlockAddress, res, _addressesInBlockCount*4 );

	return res;
}

void BlockNode::fromBytes(unsigned char* data){
	_addresses.clear();
	bool foundHead = false;

	for(unsigned int i = 0; i < (unsigned)_addressesInBlockCount; i++){
		int val = Utils::GetInt(data, i*4);
		this->_addresses.push_back(val);

		if (!foundHead){
			if (val != 0){
				_next = i;
				foundHead = true;
			}
		}
	}
	if(!foundHead){
		_next = _addressesInBlockCount;
	}
	_nextBlockAddress = Utils::GetInt(data, _addressesInBlockCount*4);
}

bool BlockNode::isFull(){
	bool result = (_next == 0);

	return result;
}

bool BlockNode::isEmpty(){
	bool result = (_next == _addressesInBlockCount);

	return result;
}

int BlockNode::removeAddress(){
	if (isEmpty()){
		return -1;
	}

	int result = _addresses.at(_next);
	_addresses[_next] = 0;
	_next++;

	return result;
}

int BlockNode::addAddress(int address){
	if (isFull()){
		return -1;
	}

	 _next--;
	_addresses[_next] = address;

	return 0;
}








